package com.yjz.log.print.view;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.yjz.log.R;
import com.yjz.log.config.YLogType;

import java.util.ArrayList;
import java.util.List;

/**
 * 作用 :
 * 作者 : yjz
 * 时间 : 2024/9/14 15:54
 */
public class LogViewAdapter extends RecyclerView.Adapter<LogViewAdapter.LogViewHolder> {

    private LayoutInflater inflater;

    private List<LogModel> logs = new ArrayList<>();

    LogViewAdapter(LayoutInflater inflater) {
        this.inflater = inflater;
    }

    void addItem(LogModel logItem) {
        logs.add(logItem);
        notifyItemInserted(logs.size() - 1);
    }

    @NonNull
    @Override
    public LogViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = inflater.inflate(R.layout.ylog_view_item, parent, false);
        return new LogViewAdapter.LogViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(LogViewAdapter.LogViewHolder holder, int position) {
        LogModel logItem = logs.get(position);

        int color = getHighlightColor(logItem.level);
        holder.tagView.setTextColor(color);
        holder.messageView.setTextColor(color);

        holder.tagView.setText(logItem.getFlattened());
        holder.messageView.setText(logItem.log);
    }

    /**
     * 跟进log级别获取不同的高了颜色
     *
     * @param logLevel log 级别
     * @return 高亮的颜色
     */
    private int getHighlightColor(int logLevel) {
        int highlight;
        switch (logLevel) {
            case YLogType.V:
                highlight = 0xffbbbbbb;
                break;
            case YLogType.D:
                highlight = 0xffffffff;
                break;
            case YLogType.I:
                highlight = 0xff6a8759;
                break;
            case YLogType.W:
                highlight = 0xffbbb529;
                break;
            case YLogType.E:
                highlight = 0xffff6b68;
                break;
            default:
                highlight = 0xffffff00;
                break;
        }
        return highlight;
    }

    @Override
    public int getItemCount() {
        return logs.size();
    }

    public static class LogViewHolder extends RecyclerView.ViewHolder {

        TextView tagView;
        TextView messageView;

        LogViewHolder(View itemView) {
            super(itemView);
            tagView = itemView.findViewById(R.id.tag);
            messageView = itemView.findViewById(R.id.message);
        }
    }
}
